<!-- PlayTwo.vue -->
<template>
  <div class="play-section">
    <h2 class="play-title">
      <span>{{ title }}</span>
      <el-button type="primary" :loading="loading" @click="saveAs">保存</el-button>
    </h2>
    <div>
      <el-input placeholder="请输入名称" class="input-with-select" style="width: 70%; margin: 3px 0 10px 0" v-model="form.buyName">
        <el-button slot="prepend">用户名称</el-button>
      </el-input>
       <el-select v-model="form.sheng"  style="width: 28%; margin: 3px 0 10px 1.5%" placeholder="请选择">
    <el-option
      v-for="item in dictList"
      :key="item.dictValue"
      :label="item.dictLabel"
      :value="item.dictValue">
    </el-option>
  </el-select>
    </div>
    <div class="dis-flex">
      <el-input
        type="textarea"
        v-model="form.localNoArrStr"
        @input="handleInput"
        show-word-limit
        maxlength="20000"
        :autosize="{ minRows: 6, maxRows: 8 }"
        placeholder="每行输入一个号码，系统将按行提取纯数字"
      >
      </el-input>
    </div>

    <div style="margin-top: 15px">
      <el-input placeholder="请输入倍数" class="input-with-select" min="0" style="width: 20%"  @input="validateMultiple" type="number" v-model="form.multiple">
        <el-button slot="append">倍</el-button>
      </el-input>
    </div>

    <div >
       <p class="result-text">提取结果：
            <span style="padding:10px;" v-for="(value, index) in (form.lotteryNo || '').split(',')" :key="index">{{ value }}</span>
        </p>
        <p v-if="form.lotteryNo">
            共<span class="font-red">{{ (form.lotteryNo || '').split(',').length }}</span>组
        </p>
    </div>
    <CustomDialog @close="form = {}" ref="CustomDialog"></CustomDialog>
  </div>
</template>

<script>
import { saveLotteryVo2 } from "@/api/bussiness";
import CustomDialog from "../modules/CustomDialog.vue";

export default {
  name: "PlayTwo",
  components: {
    CustomDialog,
  },
  props: {
    // 接收父组件传入的初始值
    noArrStr: {
      type: String,
      default: "",
    },
    title: {
      type: String,
      default: "",
    },
    lotteryType: {
      type: String,
      default: "",
    },
    lotteryNo: {
      type: String,
      default: "",
    },
    dictList: {
        type: Array,
        default:[],
    },
  },
  data() {
    return {
      loading: false,
      form: {
        localNoArrStr: "",
        lotteryNo: "",
        buyName: "", //用户名称
        lotteryType: this.lotteryType,
          multiple: 0, //购买倍数
        sheng:''
      },
    };
  },
  watch: {
    // 监听父组件传入的值变化
        noArrStr(val) {
            this.form.localNoArrStr = val;
        },
        dictList: {
            handler(newVal) {
                this.initShengFromLocalStorage();
            },
            immediate: true // 立即执行一次，组件创建时也会执行
        }
    },
   mounted() {
       // 页面初始化时从localStorage取出存储的省值
    this.$nextTick(() => {
      this.initShengFromLocalStorage();
    });
  
    
  },
    methods: {
    validateMultiple(value) {
    // 确保输入值不小于0
        if (value < 0) {
            this.form.multiple = 0;
        }
    },
  
    shengCHange (val) { 
        if (val) {
            localStorage.setItem('selectedSheng', val);
        }
        },
     initShengFromLocalStorage() {
          try {
                const savedSheng = localStorage.getItem('selectedSheng');
                if (savedSheng) {
                this.form.sheng = savedSheng;
                } else if (this.dictList && this.dictList.length > 0) {
                // 如果本地存储中没有值，则默认选中第一个
                this.form.sheng = this.dictList[0].dictValue;
                }
            } catch (error) {
                console.error('从localStorage读取省值时出错:', error);
            }
        },
          getFileNameFromHeaders(headers) {
      const contentDisposition = headers['Content-Disposition'][0];
      const match = contentDisposition.match(/filename="(.+)"/);
      return match ? match[1] : 'document.pdf';
    },
    saveAs() {
      this.loading = true;
      if (!this.form.buyName) {
          this.$message.error("请输入" + this.title + "名称！");
          this.loading = false;
        return;
      }
      if (!this.form.lotteryNo) {
          this.$message.error("请输入" + this.title + "彩票单号");
          this.loading = false;
        return;
      }
      if (!this.form.multiple) {
          this.$message.error("请输入" + this.title + "倍");
          this.loading = false;
        return;
      }
      this.form.lotteryType = this.lotteryType;
      saveLotteryVo2(this.form).then(res => {
       if (res.code == 200) {

        const pdfContent = res.data.body;
        const fileName = this.getFileNameFromHeaders(res.data.headers);

        // 将Base64转换为Blob
        const byteCharacters = atob(pdfContent);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: 'application/pdf' });

        // 创建URL并打开
        const blobUrl = URL.createObjectURL(blob);
        window.open(blobUrl, '_blank');

        // 清理URL对象
        setTimeout(() => URL.revokeObjectURL(blobUrl), 100);

          console.log(res)
          this.$message.success("保存成功！");
          /* this.$refs.CustomDialog.open(this.form);*/
            this.form = {
                buyGroup:0,
                multiple: 0,
                 sheng:localStorage.getItem('selectedSheng')
            };

            this.$emit('close') 
          this.loading = false;
        } else {
          console.log("我保存失败了");
          this.$message.error("保存失败！");
           this.form = {
              buyGroup:0,
              multiple:0,
          };
          this.$emit('close')
          this.loading = false;
        }
      });
       this.loading = false;
    },

    handleInput(value) {
      this.form.localNoArrStr = value;
      this.extractNumbersByLine(value);
      // 向父组件传递输入变化
      this.$emit("update:noArrStr", value);
      this.$emit("update:lotteryNo", this.lotteryNo);
    },

    extractNumbersByLine(values) {
      if (!values) {
        this.form.lotteryNo = "";
        return;
      }

      // 定义分隔符数组
      const separators = ["/", "，", ",", "+"];

      // 创建正则表达式，匹配所有分隔符
      const regex = new RegExp(`[${separators.map(s => "\\" + s).join("")}]`);

      // 先按换行符分割，再按其他分隔符分割
      const lines = values.split(/\r?\n/);
      const validNumbers = [];

      // 遍历每一行
      lines.forEach(line => {
        // 如果行中包含其他分隔符，则进一步分割
        if (regex.test(line)) {
          const parts = line.split(regex);
          parts.forEach(part => {
            const cleanedPart = part.replace(/\D/g, "");
            if (cleanedPart) {
              validNumbers.push(cleanedPart);
            }
          });
        } else {
          // 去除空格并提取所有数字
          const cleanedLine = line.replace(/\D/g, "");
          if (cleanedLine) {
            validNumbers.push(cleanedLine);
          }
        }
      });

      this.form.lotteryNo = validNumbers.join(",");
    },
  },
};
</script>

<style scoped>
.play-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
}
.result-text {
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: auto;
  max-width: 100%;
  margin-top: 10px;
  padding: 5px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.play-title {
  font-size: 18px;
  color: #409eff;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  margin: 5px 0 10px 0;
  padding-bottom: 10px;
}

.dis-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.font-red {
  color: rgb(226, 24, 24);
  font-weight: 700;
  margin: 0 5px;
  font-size: 19px;
}

.input-with-select ::v-deep .el-input-group__append {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}
</style>
